﻿using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using SpectrumAnalyser.Common.Csv;
using SpectrumAnalyser.Data.Files.SpectrumFileReaderContracts;
using SpectrumAnalyser.ModelObjects;
using SpectrumAnalyser.ModelObjects.Enum;
using SpectrumAnalyser.ModelObjects.Interfaces;
using SpectrumFileReaderType = SpectrumAnalyser.ModelObjects.Enum.SpectrumFileReaderType;

namespace SpectrumAnalyser.Data.Files.SpectrumFileReader
{
    public class SpectrumFileReader : ISpectrumFileReader
    {
        public SpectrumFile ReadSpectrumFile(FileInfo fileInfo)
        {
            var spectrumFile = new SpectrumFile {FileName = fileInfo.Name};

            DataTable table = CsvReader.ReadTable(fileInfo.FullName, ' ', false, true, true);

            spectrumFile.DataPoints = new List<IDataPoint>();
            var numberFormatInfo = new NumberFormatInfo {NumberDecimalSeparator = ","};

            foreach (DataRow row in table.Rows)
            {
                spectrumFile.DataPoints.Add(new SpectrumDataPoint
                    {
                        SpectrumPoint =
                            new SpectrumPoint(double.Parse(row[1].ToString(), numberFormatInfo),
                                      double.Parse(row[2].ToString(), numberFormatInfo))
                    });
            }

            spectrumFile.WavelengthMeasure =
                spectrumFile.DataPoints.Any(x => x.SpectrumPoint.X > 200 && x.SpectrumPoint.X < 1000)
                    ? WavelengthMeasure.Nanometers
                    : WavelengthMeasure.Angstroms;

            return spectrumFile;
        }

        public string SpectrumFileReaderType
        {
            get { return "Default"; }
        }

        public IList<string> AcceptableExtensions
        {
            get { return new List<string> {"*.txt"}; }
        }
    }
}